package com.winning.sx.microframework.common.util;


import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ValidateUtil {
    public static void NullFieldValidate(Object instance) throws Exception {
        Field[] fields = instance.getClass().getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            Object fieldValue = runGetter(field, instance);

            boolean isAnnotationNotNull = field.isAnnotationPresent(NotNull.class);
            if (isAnnotationNotNull && fieldValue == null) {
                throw new Exception(fieldName + "不能为空");
            }
        }
    }
    private static Object runGetter(Field field, Object instance) throws Exception {
        // MZ: Find the correct method
        for (Method method : instance.getClass().getDeclaredMethods()) {
            if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3))) {
                if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase())) {
                    // MZ: Method found, run it
                    try {
                        return method.invoke(instance);
                    } catch ( InvocationTargetException e){
                        throw new Exception("不能找到该对象的方法: " + method.getName());
                    } catch (IllegalAccessException e) {
                        throw new Exception("不能找到该对象的方法: " + method.getName());
                    }
                }
            }
        }
        return null;
    }

}
